package club.vann.nowcoder;

import club.vann.nowcoder.common.TreeNode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;

/**
 * <p>难度：Medium</p>
 * <p>题目：二叉树的之字形遍历</p>
 * <p>描述：给定一个二叉树，返回该二叉树的之字形层序遍历，（第一层从左向右，下一层从右向左，一直这样交替）
 * 例如：
 * 给定的二叉树是{3,9,20,#,#,15,7},
 *
 * 该二叉树之字形层序遍历的结果是
 * [
 * [3],
 * [20,9],
 * [15,7]
 * ]
 * 示例1
 * 输入
 * 复制
 * {1,#,2}
 * 返回值
 * 复制
 * [[1],[2]]</p>
 * @author vann
 * @program now-coder
 * @description
 * @date 2021-03-13:17:20:46
 */
public class NC14 {
    public static void main(String[] args) {
        NC14 nc14 = new NC14();
        ArrayList<ArrayList<Integer>> res = null;
        res = nc14.zigzagLevelOrder(TestCase.NODE);
        res = nc14.zigzagLevelOrder(TestCase.NODE1);
        System.out.println("Success");
    }

    /**
     *
     * @param root TreeNode类
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder (TreeNode root) {
        // write code here
        ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
        if(root == null) {
            return ans;
        }
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.push(root);

        int flag = 1;
        while(!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            int count = 0;
            while(!queue.isEmpty() && count < size) {
                TreeNode node = queue.pollFirst();
                if(node.left != null) {
                    queue.addLast(node.left);
                }

                if(node.right != null) {
                    queue.addLast(node.right);
                }

                list.add(node.val);
                count ++;
            }
            if(flag == -1) {
                Collections.reverse(list);
            }
            flag = flag * -1;
            ans.add(list);
        }
        return ans;
    }

    static class TestCase {
        public static TreeNode NODE = TreeNode.deserialize("[1,#,2]");

        public static TreeNode NODE1 = TreeNode.deserialize("[3,9,20,#,#,15,7]");
    }
}
